package cn.sciento.farm.devicemanager.fjhsxq.schedule;

import cn.sciento.farm.devicemanager.fjhsxq.exception.ResposeException;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.BaseReq;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.ReqHeader;
import cn.sciento.farm.devicemanager.dao.entity.FjhsxqUploadLog;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.config.UploadConfig;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.upload.UploadLandData;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.upload.UploadSensorData;
import cn.sciento.farm.devicemanager.fjhsxq.model.common.upload.UploadSensorTotal;
import cn.sciento.farm.devicemanager.fjhsxq.upload.UploadInfoService;
import cn.sciento.farm.devicemanager.fjhsxq.utils.EncrypUtils;
import cn.sciento.farm.devicemanager.fjhsxq.utils.HttpClientPost;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Component
public class SendMessage {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UploadInfoService uploadInfoService;

    @Autowired
    private UploadConfig uploadConfig;

    private String sendInfoMessage(String sensorInfo, String path){
        Map<String, Object> request = HttpClientPost.request(path, sensorInfo);
        logger.info("响应报文 : {}",request.toString());
        Map.Entry<String, Object> next = request.entrySet().iterator().next();
        return (String)next.getValue();
    }

    @Scheduled(cron = "0 0/30 * * * ?")
    public void uploadSensorMsg() {
        UploadSensorTotal uploadSensorTotal = uploadInfoService.uploadSensorData();
        if (uploadSensorTotal != null) {
            List<UploadSensorData> sensorDatas = uploadSensorTotal.getUploadSensorDatas();
            for (UploadSensorData sensorData : sensorDatas) {
                if (sensorData.getMachineInfoList().size() >= 1 ){
                    logger.info("请求报文：{}", requestMsg(sensorData));
                    logger.info("请求地址：{}", uploadConfig.getSensorPath());
                    String message = sendInfoMessage(requestMsg(sensorData), uploadConfig.getSensorPath());
                    JSONObject jsonObject = (JSONObject) JSONObject.parseObject(message).get("header");
                    String ret = jsonObject.get("ret").toString();
                    if ("0".equals(ret)) {
                        logger.info(jsonObject.get("msg").toString());
                    }else {
                        FjhsxqUploadLog fjhsxqUploadLog = new FjhsxqUploadLog();
                        fjhsxqUploadLog.setErrorCode(ret);
                        fjhsxqUploadLog.setMessage(jsonObject.get("msg").toString());
                        fjhsxqUploadLog.setCreateTime(System.currentTimeMillis());
                        uploadInfoService.save(fjhsxqUploadLog);
                        throw new ResposeException(jsonObject.get("msg").toString());
                    }
                }else {
                    logger.info("两个小时内无数据更新, 设备可能离线");
                }
            }
        }
    }


    private String requestMsg(Object sensorInfo){
        BaseReq baseReq = new BaseReq();
        baseReq.setContent(JSONObject.toJSON(sensorInfo));
        baseReq.setHeader(getReqHeader(baseReq));
        return JSONObject.toJSONString(baseReq);
    }

    private ReqHeader getReqHeader(BaseReq baseReq){
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sd.format(new Date());
        ReqHeader reqHeader = new ReqHeader();
        reqHeader.setAppId(uploadConfig.getAppId());
        reqHeader.setRequestSeq(Long.valueOf(format) + (new Random().nextInt(1000)));
        reqHeader.setRequestTime(format);
        reqHeader.setNonce(new Random().nextInt(999999));
        baseReq.setHeader(reqHeader);
        reqHeader.setMsgSignature(EncrypUtils.getMsgSignature(baseReq,uploadConfig.getKey()));
        return reqHeader;
    }

    @Scheduled(cron = "0 0 0 1 1/2 ?")
    public void batchDeleteLog(){
        Date monthBefore = getTwoMonthBefore(new Date());
        long time = monthBefore.getTime();
        long result = uploadInfoService.batchDeleteLogByCreateTime(time);
        logger.info("已删除当前时间两个月前的"+ result+"条日志");
    }

    // 获取当前日期2个月前的时间
    private Date getTwoMonthBefore(Date date){
        // 获取当前时间
        Calendar c = Calendar.getInstance(); //得到日历
        c.setTime(date);//把当前时间赋给日历
        c.add(c.MONTH, -2); //设置为前2月，可根据需求进行修改
        c.set(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR_OF_DAY, 00);
        c.set(Calendar.MINUTE, 00);
        c.set(Calendar.SECOND, 00);
        return c.getTime();
    }

//    @Scheduled(cron = "0/30 * * * * ?")
//    public void uploadLandMsg() {
//        UploadLandData landInfo = uploadInfoService.uploadLandInfoList();
//        logger.info("请求报文：{}", requestMsg(landInfo));
//        String message = sendInfoMessage(requestMsg(landInfo), uploadConfig.getLandPath());
//        JSONObject jsonObject = (JSONObject) JSONObject.parseObject(message).get("header");
//        String ret = jsonObject.get("ret").toString();
//        if ("0".equals(ret)) {
//            logger.info(jsonObject.get("msg").toString());
//        }else {
//            FjhsxqUploadLog fjhsxqUploadLog = new FjhsxqUploadLog();
//            fjhsxqUploadLog.setErrorCode(ret);
//            fjhsxqUploadLog.setMessage(jsonObject.get("msg").toString());
//            fjhsxqUploadLog.setCreateTime(System.currentTimeMillis());
//            uploadInfoService.save(fjhsxqUploadLog);
//            throw new ResposeException(jsonObject.get("msg").toString());
//        }
//    }
}
